package com.jwb.pub.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.service.AttachFileDetailService;
import com.jwb.util.MainController;
import com.jwb.util.ProtocolUtil;
import com.jwb.util.ToolsUtil;
import com.jwb.util.WxChatImgRevert;
@Slf4j
@Controller
@RequestMapping(value="/pub/attach" )
public class AttachFileDetailController extends MainController{

	@Autowired
	private AttachFileDetailService attachFileDetailService;
	
	@RequestMapping(value="/uploadsingle")
    @ResponseBody
    public String uploadSingle(HttpServletRequest req, @RequestParam(value="file")MultipartFile file) throws Exception
	{
    	JSONObject jsobject = new JSONObject();	
		try
		{
			HttpSession session = req.getSession();
			String userId = (String) session.getAttribute("userId") == null ? ""
					: (String) session.getAttribute("userId");			
			String fileName = req.getParameter("fileName") == null ? "" : req.getParameter("fileName");
			String modeName = req.getParameter("modeName") == null ? "" : req.getParameter("modeName");
			String folder = req.getParameter("folder") == null ? "" : req.getParameter("folder");
			String operCode = req.getParameter("operCode") == null ? userId : req.getParameter("operCode");
			String fileNo = req.getParameter("fileNo") == null ? ToolsUtil.get32bituuid() : req.getParameter("fileNo");
			String fileType = req.getParameter("fileType") == null ? "" : req.getParameter("fileType");
			String fileSize = req.getParameter("fileSize") == null ? "0" : req.getParameter("fileSize");
			
//			System.out.println(folder);
//			folder="/file/";
				
			String rootPath = req.getServletContext().getRealPath("/");
			// 有文件
			if (file != null)
			{
				// 文件保存路径				
				String path = rootPath+folder;	
				
				// 获取该文件扩展名并统一转换为小写
				String fileExt="";
				try
				{
					    fileExt = fileName.substring(
						fileName.lastIndexOf(".")).toLowerCase();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				// 保存在服务器端的文件名
				
				String fileId=ToolsUtil.get32bituuid();
				
				String saveName = fileId + fileExt;
				
				
				
				
				String filePath = path + "/" + saveName; //file.getInputStream()
				
				File dir = new File(path);
				if(!dir.exists()) dir.mkdirs();
				
				InputStream fis = file.getInputStream();
				FileOutputStream fos = new FileOutputStream(filePath);
				
				try
				{
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = fis.read(b)) > 0)
					{
						fos.write(b, 0, len);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					fis.close();
					fos.close();
				}			
			
				jsobject=attachFileDetailService.uploadSingle( operCode, modeName,
						 fileNo, fileId,   folder+"/"+saveName,  fileName,
						 fileType,  fileSize,  fileExt);
			   
			}
			else
			{
				jsobject.put("respCode", "-1");
				jsobject.put("respDesc", "请选择上传文件");
			}
			System.out.println("uploadSingle"+jsobject);
			
			
		}
		catch (Exception e)
		{
			
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "请选择上传失败");
			System.out.println("uploadSingle"+jsobject);
			return jsobject.toString();
		}
		//CommonUtil.prntext(jsobject.toString());
		return jsobject.toString();
	}
	
	
	
    
    
    /**
     * 获取文件列表
     * http://127.0.0.1:8080/ssm/pub/attach/uploadFileList
     * @param req
     * @return
     * @throws Exception
     */
	@RequestMapping(value="/uploadFileList")
    @ResponseBody
    public String uploadFileList(HttpServletRequest req) throws Exception
	{   
		JSONObject jsobject = new JSONObject();   
    	HttpSession session = req.getSession();
    	String userId = (String) session.getAttribute("userId") == null ? ""
				: (String) session.getAttribute("userId");
    	String currentPageNbr= req.getParameter("currentPageNbr") == null ? "1" : req.getParameter("currentPageNbr");
    	String pageSize= req.getParameter("pageSize") == null ? "10" : req.getParameter("pageSize");
    	String jsonStr = req.getParameter("jsonStr") == null ? "{}" : req.getParameter("jsonStr");
    	JSONObject jsdata = new JSONObject();
    	try {

			jsdata=JSONObject.parseObject(jsonStr);
			
			this.pageInit();
			this.getPage().setEveryPageCnt(Integer.parseInt(pageSize));
			this.getPage().setCurrentPageNbr(Integer.parseInt(currentPageNbr));
			
			jsobject = attachFileDetailService.uploadFileList(jsdata, page);
    	
		} catch (Exception e) {
			e.printStackTrace();
			jsobject.put("respCode", "-3");
			jsobject.put("respDesc", "字符串格式有误");	

		}
    	log.info("uploadFileList():" + jsobject.toString());
        return jsobject.toString();
	}	
	
	
	@RequestMapping(value="/fileDelete")
	@ResponseBody
	public String fileDelete(HttpServletRequest req) throws Exception
	{
		JSONObject jsobject = new JSONObject();	
		try
		{
		    	
		    	String fileId = req.getParameter("fileId") == null ? "" : req.getParameter("fileId");
		    	String filePath = req.getParameter("filePath") == null ? "" : req.getParameter("filePath");
		    	filePath = req.getServletContext().getRealPath("/") +filePath;
				String sqlWhere="";	
				if (null != fileId && !"".equals(fileId))
				{
					sqlWhere += " and file_id = '"+fileId+"'";
				}
				   
				System.out.println(sqlWhere);
				jsobject=attachFileDetailService.fileDelete(sqlWhere, filePath);
				
		}
		catch (Exception e)
		{
			
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "文件删除异常");
			return jsobject.toString();
		}
		return jsobject.toString();
	}
   
    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(HttpServletRequest req,
            String filename,String filepath,Model model)throws Exception {

       //下载文件路径
       String path = req.getServletContext().getRealPath("/");
       File file = new File(path + filepath);
       HttpHeaders headers = new HttpHeaders();  
       //下载显示的文件名，解决中文名称乱码问题  
       String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
       //通知浏览器以attachment（下载方式）打开图片
       headers.setContentDispositionFormData("attachment", downloadFileName); 
       //application/octet-stream ： 二进制流数据（最常见的文件下载）。
       headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
       return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
               headers, HttpStatus.CREATED);  
    }
    
    
    @RequestMapping(value="/downloadHtpForDy")
    public ResponseEntity<byte[]> downloadHtpForDy(HttpServletRequest req,
            String filename,String filepath,Model model)throws Exception { 
    	String url=filepath;
	    Map<String, String> hders = new HashMap<String, String>();
	    hders = new HashMap<String, String>();
	    hders.put("Accept", "*/*");
	    hders.put("User-Agent", "Muser-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36");	
        JSONObject jsoRsp =ToolsUtil.getHttps(url,hders) ;	
        String  location=!jsoRsp.containsKey("location") ? "" : jsoRsp.getString("location");	  
        System.out.println("location:"+location);
       //下载文件路径
       String path = req.getServletContext().getRealPath("/");
       String vFolder="/file/video";
       JSONObject paraData = new JSONObject();
	   paraData.put("rootPath", path);
	   paraData.put("floder", vFolder);
	   paraData.put("url", location);
	   
	   String filePath = ToolsUtil.getDownLoadFilePath(paraData);
       File file = new File(filePath);
       HttpHeaders headers = new HttpHeaders();  
       //下载显示的文件名，解决中文名称乱码问题  
       String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
       //通知浏览器以attachment（下载方式）打开图片
       headers.setContentDispositionFormData("attachment", downloadFileName); 
       //application/octet-stream ： 二进制流数据（最常见的文件下载）。
       headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
       return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
               headers, HttpStatus.CREATED);  
    }
    
    
    @RequestMapping(value="/downloadHtp")
    public ResponseEntity<byte[]> downloadHtp(HttpServletRequest req,
            String filename,String filepath,Model model)throws Exception { 
    	
       //下载文件路径
       String path = req.getServletContext().getRealPath("/");
       String vFolder="/file/video";
       JSONObject paraData = new JSONObject();
	   paraData.put("rootPath", path);
	   paraData.put("floder", vFolder);
	   paraData.put("url", filepath);
	   
	   String filePath = ToolsUtil.getDownLoadFilePath(paraData);
       File file = new File(filePath);
       HttpHeaders headers = new HttpHeaders();  
       //下载显示的文件名，解决中文名称乱码问题  
       String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
       //通知浏览器以attachment（下载方式）打开图片
       headers.setContentDispositionFormData("attachment", downloadFileName); 
       //application/octet-stream ： 二进制流数据（最常见的文件下载）。
       headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
       return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
               headers, HttpStatus.CREATED);  
    }
	    
	    
   /**
    * http://127.0.0.1:8080/ssm/pub/attach/filelist?jsonStr={}
    * @param req
    * @return
    * @throws Exception
    */
    @RequestMapping(value="/filelist")	 
    @ResponseBody
    public String filelist(HttpServletRequest req) throws Exception
    {   
		JSONObject jsobject = new JSONObject();   	    	
    	String currentPageNbr= req.getParameter("currentPageNbr") == null ? "1" : req.getParameter("currentPageNbr");
    	String pageSize= req.getParameter("pageSize") == null ? "10" : req.getParameter("pageSize");
    	String jsonStr = req.getParameter("jsonStr") == null ? "{}" : req.getParameter("jsonStr");
    	JSONObject jsdata = new JSONObject();
    	try {

			jsdata=JSONObject.parseObject(jsonStr);
			
			this.pageInit();
			this.getPage().setEveryPageCnt(Integer.parseInt(pageSize));
			this.getPage().setCurrentPageNbr(Integer.parseInt(currentPageNbr));
			
			jsobject = attachFileDetailService.filelist(jsdata, page);
    	
		} catch (Exception e) {
			e.printStackTrace();
			jsobject.put("respCode", "-3");
			jsobject.put("respDesc", "字符串格式有误");	

		}
    	log.info("filelist():" + jsobject.toString());
        return jsobject.toString();
	}	 
/**
 * 更新封面图
    * http://127.0.0.1:8080/ssm/pub/attach/updateCovertImage?jsonStr={}
    * @param req
    * @return
    * @throws Exception
    */
    @RequestMapping(value="/updateCovertImage")	 
    @ResponseBody
    public String updateCovertImage(HttpServletRequest req) throws Exception
    {   
    	String root="D:\\WeChat Files\\liuyn81\\FileStorage";	
		root=ToolsUtil.getProp("other.properties", "wxstorepath");
		String targetPath = root+"\\tmp";
		String convertPath = root+"\\convert";
    	JSONObject jsobject = new JSONObject();   	  
		JSONObject jsotemp = new JSONObject();   
    	String currentPageNbr= req.getParameter("currentPageNbr") == null ? "1" : req.getParameter("currentPageNbr");
    	String pageSize= req.getParameter("pageSize") == null ? "10" : req.getParameter("pageSize");
    	String jsonStr = req.getParameter("jsonStr") == null ? "{}" : req.getParameter("jsonStr");		    	
    	JSONObject jsdata = new JSONObject();
    	try {

			jsdata=JSONObject.parseObject(jsonStr);
			jsdata.put("status", "D");
			jsdata.put("file_type", "image");
			jsdata.put("pageFlag", "fenye");
			this.pageInit();
			this.getPage().setEveryPageCnt(Integer.parseInt(pageSize));
			this.getPage().setCurrentPageNbr(Integer.parseInt(currentPageNbr));					
			jsotemp = attachFileDetailService.filelist(jsdata, page);
			String convert_url="";
			if(jsotemp.containsKey("list")&&jsotemp.getJSONArray("list").size()>0)
			{
				
				for(int i=0;i<jsotemp.getJSONArray("list").size();i++)
				{
					 convert_url="";
					//重新下载原图
					 JSONObject paraData= new JSONObject();
					 paraData.put("url", jsotemp.getJSONArray("list").getJSONObject(i).getString("url"));
					 paraData.put("rootPath", targetPath);	
					 paraData.put("floder", "\\");		
					 String filePath=ToolsUtil.getDownLoadFilePath(paraData);
					 System.out.println("下载原图路径("+i+")----"+filePath);
					 String oldImgPath=filePath;
			         String newImgPath=filePath;
			         newImgPath=newImgPath.replace("tmp", "convert");
			         boolean flag=WxChatImgRevert.imgConvert(oldImgPath,newImgPath);
			         System.out.println(flag); 
			         if(flag)
			         {
				         String authorToken=ToolsUtil.getProp("other.properties", "authorTokenMp");		
						 JSONObject reqDataC = new JSONObject();	
						 JSONObject jsoRespC = new JSONObject();	
						 reqDataC.put("filePath", newImgPath);	
						 jsoRespC=ProtocolUtil.uploadImageFileForMp(authorToken, reqDataC);
						 System.out.println("uploadFileForMp:task(cover_image)========"+jsoRespC);
						 if("0".equals(jsoRespC.getString("respCode")))
			  			 {
							  convert_url=jsoRespC.getJSONObject("result").getString("key");
			  			 }
			         }		
					 
					 
					 JSONObject reqData = new JSONObject();
					 reqData.put("file_id", jsotemp.getJSONArray("list").getJSONObject(i).getString("file_id"));
		  			 reqData.put("file_path", jsotemp.getJSONArray("list").getJSONObject(i).getString("file_path"));
		  			 reqData.put("domain_name",jsotemp.getJSONArray("list").getJSONObject(i).getString("domain_name"));
		  			 reqData.put("source",jsotemp.getJSONArray("list").getJSONObject(i).getString("source"));				  			 
		  			 reqData.put("info",jsotemp.getJSONArray("list").getJSONObject(i).getString("info") );
		  			 reqData.put("url",jsotemp.getJSONArray("list").getJSONObject(i).getString("url") );
		  			 reqData.put("file_type",jsotemp.getJSONArray("list").getJSONObject(i).getString("file_type") );
		  			 reqData.put("convert_url",jsotemp.getJSONArray("list").getJSONObject(i).getString("domain_name")+convert_url );
		  			 reqData.put("status","A" );
		  			 jsobject=attachFileDetailService.fileInfoSave(reqData);
				}
				
			}
			else
			{
				log.info("updateCovertImage():" + jsotemp.toString());
		        return jsotemp.toString();
			}
			
    	
		} catch (Exception e) {
			e.printStackTrace();
			jsobject.put("respCode", "-3");
			jsobject.put("respDesc", "字符串格式有误");	

		}
    	  ToolsUtil.deleteFile(new File(targetPath));
          ToolsUtil.deleteFile(new File(convertPath));	
    	  log.info("updateCovertImage():" + jsobject.toString());
          return jsobject.toString();
	}
    
    
    @RequestMapping(value="/fileDel")
	@ResponseBody
	public String fileDel(HttpServletRequest req) throws Exception
	{
		JSONObject jsobject = new JSONObject();	
		try
		{
		    	
		    	String fileId = req.getParameter("file_id") == null ? "" : req.getParameter("file_id");
		    	String filePath = req.getParameter("filePath") == null ? "" : req.getParameter("filePath");
		    	filePath = req.getServletContext().getRealPath("/") +filePath;
				String sqlWhere="";	
				if (null != fileId && !"".equals(fileId))
				{
					sqlWhere += " and file_id = '"+fileId+"'";
				}
				   
				System.out.println(sqlWhere);
				jsobject=attachFileDetailService.fileDel(sqlWhere, filePath);
				
		}
		catch (Exception e)
		{
			
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "文件删除异常");
			return jsobject.toString();
		}
		return jsobject.toString();
	}
    
    
    @RequestMapping(value="/addname")
	@ResponseBody
	public String addname(HttpServletRequest req) throws Exception
	{
		JSONObject jsobject = new JSONObject();	
		try
		{
		    	
		    	String name = req.getParameter("name") == null ? "" : req.getParameter("name");
		    	JSONObject jsdata = new JSONObject();	
		    	jsdata.put("name", name);
				jsobject=attachFileDetailService.addname(jsdata);
				
		}
		catch (Exception e)
		{
			
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "系统异常");
			return jsobject.toString();
		}
		return jsobject.toString();
	}
    
    
    
    /**
     * http://127.0.0.1:8080/ssm/pub/attach/nodelist?jsonStr={}
     * @param req
     * @return
     * @throws Exception
     */
     @RequestMapping(value="/nodelist")	 
     @ResponseBody
     public String nodelist(HttpServletRequest req) throws Exception
     {   
    	 String path = req.getServletContext().getRealPath("/");
    	 
    	JSONObject jsobject = new JSONObject();  
        String jsonStr = req.getParameter("jsonStr") == null ? "{}" : req.getParameter("jsonStr");
     	JSONObject jsdata = new JSONObject();
     	JSONArray jsonArray = new JSONArray();
     	try {

 			jsdata=JSONObject.parseObject(jsonStr);		
 			 String id = jsdata.containsKey("id")?jsdata.getString("id"):path;
 			 jsonArray=ToolsUtil.getFiles(id);		 
 			 if(jsonArray==null)
 			 {
 				jsobject.put("respCode", "-1");
 	 			jsobject.put("respDesc", "获取文件列表失败");	
 			 }
 			 else
 			 {
 				jsobject.put("respCode", "0");
 	 			jsobject.put("respDesc", "成功");	
 	 			jsobject.put("list", jsonArray);	
 			 }
     	
 		} catch (Exception e) {
 			e.printStackTrace();
 			jsobject.put("respCode", "-3");
 			jsobject.put("respDesc", "字符串格式有误");	

 		}
     	log.info("nodelist():" + jsobject.toString());
     	return jsobject.toString();	
 	 }	
}
